<?php

/**
 * calendar actions.
 *
 * @package    sf_sandbox
 * @subpackage calendarentry
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class calendarActions extends autocalendarActions
{
    public function executeIndex()
    {
        $this->forward('calendar', 'calendar');
    }
    
    /**
     * 
     * Change status, to deleted if was approved, else to approwed
     */
    public function executeChangestatus()
    {
        /* @var $entry Calendar */
        $id = (int)$this->getRequestParameter('id');
        $entry = CalendarPeer::retrieveByPK($id);
        $this->forward404Unless($entry);
        if($entry->getStatusId() == MyConstants::STATUS_APPROVED)
        {
            $entry->setStatusId(MyConstants::STATUS_DELETED);
            $entry->save();
            return $this->redirect('calendar/list?id=' . $id);
        }else 
        {
            $entry->setStatusId(MyConstants::STATUS_APPROVED);
            $entry->save();
            return $this->redirect('calendar/list?id=' . $id);
        }
        
    }
    /**
     * 
     * set default status_id new (1)
     * @param Calendar object
     */
    protected function getCalendarOrCreate($id = 'id')
    {
        /* @var $calendar Calendar */
        $calendar = parent::getCalendarOrCreate($id);
        $calendar->setCulture($this->getUser()->getCulture());
        if($calendar->getStatusId()<1);
        {
            $calendar->setStatusId(MyConstants::STATUS_NEW);
        }
        return $calendar;
    }
    protected function updateCalendarFromRequest()
    {
        parent::updateCalendarFromRequest();
        $calendar = $this->getRequestParameter('calendar');
        if (isset($calendar['latitude']) && !empty($calendar['latitude']))
        {
            $this->calendar->setPointLatitude($calendar['latitude']);
        }
        if (isset($calendar['longitude']) && !empty($calendar['longitude']))
        {
            $this->calendar->setPointLongitude($calendar['longitude']);
        }
        if (isset($calendar['address']) && !empty($calendar['address']))
        {
            $this->calendar->setAddress($calendar['address']);
        }
        if (isset($calendar['visible_role']) && !empty($calendar['visible_role']))
        {
            /* @var calendar Calendar */
            $str = '';
            foreach ( $calendar['visible_role'] as $role )
            {
                $str = $str . $role . ':';
            }
            $this->calendar->setUserRoles($str);
        }else 
        {
            $this->calendar->setUserRoles('');
        }
        if (isset($calendar['is_personal']))
        {
            $this->calendar->setIsPersonal($calendar['is_personal']);
        }else 
        {
            $this->calendar->setIsPersonal(0);
        }
        if (isset($calendar['duration']))
        {
            $this->calendar->setDuration($calendar['duration']);
        }
        if (isset($calendar['metric']))
        {
            $this->calendar->setDurationMetric($calendar['metric']);
        }
        if (isset($calendar['times_to_repeat']))
        {
            $this->calendar->setTimesToRepeat($calendar['times_to_repeat']);
        }
        $this->calendar->setUserId(get_user_id());
        
    }
    
    protected function saveCalendar($calendar)
    {
        $arCalendar = $this->getRequestParameter('calendar');
        $str = '';
        foreach ($arCalendar as $val)
        {
            $str = $str . $val;
        }
        $seq = md5($calendar->getId() . $str );
        // repeated event
        if( ($this->getRequestParameter('calendarrepeat') > 0) )
        {
            $tmb = strtotime($arCalendar['begins']['year'] 
                        . '-' 
                        . $arCalendar['begins']['month'] 
                        . '-' 
                        . $arCalendar['begins']['day']
                        . ' '
                        . $arCalendar['begins']['hour']
                        . ':'
                        . $arCalendar['begins']['minute']);
            //$tmb = strtotime(str_replace('.', '-', $arCalendar['begins']));
            $date = date('Y-n-j H:i', $tmb);
            Calendar::deleteBySeq($calendar->getSeqId());
            
            // one day event
            if( !isset($arCalendar['ends_at']) )
            {
                Calendar::createRepeatedEvents($calendar, $seq, $date );
            }else 
                // continuous event
            {
                if( $arCalendar['start_at'] > 0 )
                {
                    //???
                }else 
                {
                    throw new Exception('Start date not set.');
                }
            }
        }else 
        {
            if ($this->getRequestParameter('update_all') && $calendar->getSeqId() != '' )
            {
                $date = $calendar->getFirstEventStart();
                Calendar::deleteBySeq($calendar->getSeqId());
                Calendar::createRepeatedEvents($calendar, $seq, $date);
                return $this->redirect('calendar/list');
            }else 
            { 
                $calendar->save();
            }
        }
    }
    
    public function executeCalendar()
    {
        /* @todo: coordinates to maps.google.com  for event place */
        $thisDate = $this->getRequestParameter('id', date('Y-n'));
        /* @var $arDaysInMonth[$i] CalendarDayItem */
        $arDaysInMonth = array();
        $thisDateFormat = $thisDate . '-1';
        $thisDateTm = strtotime($thisDateFormat);
        
        $thisMonthFirst = date($thisDateFormat);
        $thisMonth = date('n', $thisDateTm);
        $qntThisMonthDays = date('t', $thisDateTm);
        $thisMonthFirstTm = $thisDateTm;
        $thisMonthStartsAtWeekDay = date('N',$thisDateTm) - 1;
        
        $FirstTm = $thisMonthFirstTm;
        $day = date('j', $FirstTm);
        for( $i = $thisMonthStartsAtWeekDay; $i < $qntThisMonthDays +$thisMonthStartsAtWeekDay; $i++ )
        {
            $arDaysInMonth[$i] = new CalendarDayItem();
//          $arDaysInMonth[$i]->EntriesQnt = Calendar::getCountEvents(date('Y-n-j', $FirstTm));
            $arDaysInMonth[$i]->Date = date('Y-n-j', $FirstTm);
            $arDaysInMonth[$i]->Day = $day;
//          $arDaysInMonth[$i]->Title = date('Y-m')
            $FirstTm = $FirstTm + 60*60*24;
            $day = date('j', $FirstTm);
        }
        $arrEntries = Calendar::getMonthEvents(date('Y', $thisDateTm)
                                            , date('n',$thisDateTm));
        /* @var $entry Calendar */
        foreach ($arrEntries as $entry )
        {
            $dayEntry = date('j', strtotime($entry->getStartAt()));
            $arDaysInMonth[$dayEntry+$thisMonthStartsAtWeekDay - 1]->Title = 
                    $arDaysInMonth[$dayEntry+$thisMonthStartsAtWeekDay - 1]->Title 
                    . '<br/>'
                    . '<b>'
                    . $entry->getStartAt()
                    . '</b>&nbsp;'
                    . $entry->getTitle();
            $arDaysInMonth[$dayEntry+$thisMonthStartsAtWeekDay - 1]->EntriesQnt = 
                    $arDaysInMonth[$dayEntry+$thisMonthStartsAtWeekDay - 1]->EntriesQnt + 1;
        }
        for( $i = 0 ; $i < $thisMonthStartsAtWeekDay ; $i++ )
        {
            
            $arDaysInMonth[$i] = new CalendarDayItem();
        }
        $this->arCalendar = $arDaysInMonth;
        $arMonthNamesTranslated = sfDateTimeFormatInfo::getInstance($this->getUser()->getCulture())->getMonthNames();
        
        $thisYear = date('Y', $thisDateTm);
        // if last or first month.
        if($thisMonth == 12)
        {
            $this->nextDate = ($thisYear + 1) . '-1';
            $this->prevDate = $thisYear . '-' . ($thisMonth-1);
        }elseif($thisMonth == 1)
        {
            $this->nextDate = $thisYear . '-' . ($thisMonth+1);
            $this->prevDate = ($thisYear-1) . '-12';
        }else 
        {
            $this->nextDate = $thisYear . '-' . ($thisMonth+1);
            $this->prevDate = $thisYear . '-' . ($thisMonth-1);
        }
        $this->month = $arMonthNamesTranslated[$thisMonth-1];
        $this->tm = $thisDateTm;
    }
    public function executeEvents()
    {
        $date = $this->getRequestParameter('id', date('Y-n-j'));
        $this->arEvents = Calendar::getEventsAll($date, 1);
    }
    public function executeSaveinfo()
    {
        $this->all = $this->getRequestParameter('all', 0);
        $this->calendar = CalendarPeer::retrieveByPK($this->getRequestParameter('id', 0));
        $this->update = $this->getRequestParameter('update', 0);
        $this->forward404Unless($this->calendar);
    }
    public function executeEventsmonth()
    {
        $tm = $this->getRequestParameter('id', strtotime(date('Y-n-j')));
        $this->arEvents = Calendar::getMonthEvents(date('Y', $tm), date('n', $tm));
        $this->setTemplate('events');
    }
    public function executeRepeat()
    {
        $this->calendar = CalendarPeer::retrieveByPK($this->getRequestParameter('id', 0));
    }
    
	/**
	 * 
	 * get events from calendar
	 * @param year, month, day during days count
	 * 
	 * return object with events
	 */
	public function executeGetevents()
	{
		/* @var $entry CalendarEntry */
		$year = (int)$this->getRequestParameter('year', date('Y'));
		$month = (int)$this->getRequestParameter('month', date('m'));
		$month = str_pad($month, '2', '0', STR_PAD_LEFT);
		$day = (int)$this->getRequestParameter('day', date('d') );
		$day = str_pad($day, '2', '0', STR_PAD_LEFT); 
		//$day = 15;
		
		$time = '00:00:00';
		
		$duration = (int)$this->getRequestParameter('days', date('t') );

		$this->date = $year . '-' . $month . '-' . $day . ' ' . $time;
		$this->dateStart = $year . '-' . $month . '-' . $day;
		$this->dateEnd = date('Y-m-d', strtotime(date('Y-m-d', strtotime($this->date)) . ' +' . ($duration-1) . ' day') );
		$this->calendars = Calendar::getEventsAll($this->date, $duration);
		
		//debugvar($this->calendars, 'calendars');
		
		//sfView::NONE;
	}


	/**
	 * 
	 * get events from calendar for year, month
	 * @param year, month
	 * 
	 * return object with events
	 */
	public function executeGetmonthevents()
	{
		/* @var $entry CalendarEntry */
		$year = (int)$this->getRequestParameter('year', date('Y'));
		$month = (int)$this->getRequestParameter('month', date('m'));
		$month = str_pad($month, '2', '0', STR_PAD_LEFT);
		
		$this->dateStart = $year . '-' . $month . '-01';
		$this->dateEnd = $year . '-' . $month . '-' . date('t', strtotime(date('Y-m-d', strtotime($this->dateStart))) );
		$this->calendars = Calendar::getMonthEvents($year, $month);
		
		//debugvar($this->calendars, 'calendars');
		
		$this->setTemplate('getevents');
		//sfView::NONE;
	}
	

	/**
	 * 
	 * get calendar object by id
	 * @param id
	 * 
	 * return calendar object
	 */
	public function executeShow()
	{
		/* @var $entry CalendarEntry */
		$this->calendar = CalendarPeer::retrieveByPK($this->getRequestParameter('id'));
		$this->forward404Unless($this->calendar);
	}
	
	public function executeDelete()
    {
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            $calendar = CalendarPeer::retrieveByPK($this->getRequestParameter('id'));
            $this->forward404Unless($calendar);
            $calendar->delete();
            $this->redirect('calendar/list');
        }
        $this->calendar = CalendarPeer::retrieveByPK($this->getRequestParameter('id'));
    }

}
